package com.haois.mp.database.util.mp;

import com.haois.mp.database.commom.constant.StatusCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;


/**
 * Created by haol on 2017/3/16.
 */
public class HandleCookie {

    private static Logger logger = LoggerFactory.getLogger(HandleCookie.class);

    private HandleToken handleToken = new HandleToken();


    public static HttpServletResponse saveCookie(HttpServletResponse response,
                                                 String cookieName, String cookieValue) {

        Cookie cookie = new Cookie(cookieName, cookieValue);
        cookie.setHttpOnly(true);
        cookie.setPath("/");
        try {
            URLEncoder.encode(cookieValue, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.addCookie(cookie);
        // logger.info("保存cookie到本地,name =[{}]",cookieName);
        return response;
    }

    public static HttpServletResponse deleteCookie(HttpServletResponse response, String name) {
        Cookie cookie = new Cookie(name, null);
        cookie.setMaxAge(0);
        cookie.setPath("/");
        response.addCookie(cookie);
        return response;
    }

    public static Cookie getCookieByName(HttpServletRequest request, String name) {
        Cookie[] cookies = request.getCookies();
        Cookie cookie = null;
        for (Cookie cookie_ : cookies) {
            if (cookie_.getName().equals(name)) {
                cookie = cookie_;
            }
        }
        return cookie;
    }

    public static String getValueByName(HttpServletRequest request, String name) {
            String token = "";
            String from = request.getHeader("fromWhere");
            if (StatusCode.COOKIE_JWT_APP.equals(name) && "weChat".equals(from)){
                token = request.getHeader("JSONWebTokens");
            }else {
                Cookie cookie = getCookieByName(request, name);
                if (cookie == null){
                    throw new NullPointerException("cookie信息不存在");
                }
                token = cookie.getValue();
            }
            return token;
    }


    public static HttpServletResponse updateCookie(String subject, HttpServletResponse response, Date IssuedTime, String cookieName) {
        ProduceJwt produceJwt = new ProduceJwt();
        String jwt =null;
        // logger.info("更新cookie到本地,name =[{}],value=[{}]");
        return HandleCookie.saveCookie(response, cookieName, jwt);
    }

}


